package best.driver.android.View;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import best.driver.android.R;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

/**
 * Created by shuming.ai on 15/1/17.
 */
public class BasePullToRefreshListView extends PullToRefreshListView {

    private static final String TAG = "BasePullToRefreshListView";

    private Context mContext;

    private View mFooterView;
    private LinearLayout mFooterContentView;
    private ImageView mFooterDivider;
    private TextView mFooterTextView;
    private ProgressBar mFooterLoadingView;

    private boolean isAutoLoadMoreEnabled = false;
    private boolean isAutoLoadMoreLoading = false;

    private OnPullDownListener mOnPullDownListener;

    public BasePullToRefreshListView(Context context) {
        super(context);
        initBaseAttr(context);
    }

    public BasePullToRefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initBaseAttr(context, attrs);
    }

    public BasePullToRefreshListView(Context context, Mode mode) {
        super(context, mode);
        initBaseAttr(context);
    }

    public BasePullToRefreshListView(Context context, Mode mode,
                                     AnimationStyle style) {
        super(context, mode, style);
        initBaseAttr(context);
    }

    private void initFooterBackground(AttributeSet attrs) {
        // Styleables from XML
        TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.PullToRefresh);
        if (a.hasValue(R.styleable.PullToRefresh_ptrFooterBackground)) {
            Drawable background = a.getDrawable(R.styleable.PullToRefresh_ptrFooterBackground);
            if (null != background) {
                mFooterContentView.setBackgroundDrawable(background);
            }
        }
        if (a.hasValue(R.styleable.PullToRefresh_ptrFooterSubTextColor)) {
            ColorStateList colors = a
                    .getColorStateList(R.styleable.PullToRefresh_ptrFooterSubTextColor);
            if (null != colors) {
                mFooterTextView.setTextColor(colors);
            }
        }
        a.recycle();
    }

    public void setTitle(String title, String release) {
        getHeaderLayout().setRefreshingLabel(title);
        getHeaderLayout().setReleaseLabel(release);
        getHeaderLayout().setPullLabel(title);
    }

    private void initBaseAttr(Context context) {
        initBaseAttr(context, null);
    }

    private void initBaseAttr(Context context, AttributeSet attr) {
        mContext = context;
        setMode(Mode.PULL_FROM_START);
        initLoadMoreFooter(attr);
        setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if(mOnPullDownListener != null) {
                    mOnPullDownListener.onRefresh();
                }
            }
        });
        setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

            @Override
            public void onLastItemVisible() {
                Log.i(TAG, "onLastItemVisible isAutoLoadMoreEnabled = " + isAutoLoadMoreEnabled
                        + " isAutoLoadMoreLoading = " + isAutoLoadMoreLoading
                        + " isFillScreenItem = " + isFillScreenItem());
                if(isAutoLoadMoreEnabled && !isAutoLoadMoreLoading && isFillScreenItem()) {
                    isAutoLoadMoreLoading = true;
                    mFooterTextView.setVisibility(View.INVISIBLE);
                    mFooterLoadingView.setVisibility(View.VISIBLE);
                    if(mOnPullDownListener != null) {
                        mOnPullDownListener.onMore();
                    }
                }
            }
        });
    }

    public void setRefreshEnabled(boolean enabled) {
        if(enabled) {
            setMode(Mode.PULL_FROM_START);
        }else {
            setMode(Mode.DISABLED);
        }
    }

    public void showAutoLoadMore() {
        this.isAutoLoadMoreEnabled = true;
        if(mFooterContentView != null && mFooterContentView.getVisibility() != View.VISIBLE) {
            mFooterContentView.setVisibility(View.VISIBLE);
        }
    }

    public void hideAutoLoadMore() {
        this.isAutoLoadMoreEnabled = false;
        if(mFooterContentView != null && mFooterContentView.getVisibility() == View.VISIBLE) {
            mFooterContentView.setVisibility(View.GONE);
        }
    }

    public void showNoMoreResult(String text) {
        this.isAutoLoadMoreEnabled = false;
        if(mFooterContentView != null && mFooterContentView.getVisibility() != View.VISIBLE) {
            mFooterContentView.setVisibility(View.VISIBLE);
            if(TextUtils.isEmpty(text)) {
                mFooterTextView.setText(text);
            }else {
                mFooterTextView.setText(R.string.load_more_no_more);
            }
        }
    }

    private void initLoadMoreFooter(AttributeSet attr) {
        mFooterView = LayoutInflater.from(mContext).inflate(R.layout.pulldown_footer, null);
        mFooterContentView = (LinearLayout) mFooterView.findViewById(R.id.pulldown_footer_content);
        mFooterDivider = (ImageView) mFooterView.findViewById(R.id.pulldown_footer_divider);
        mFooterTextView = (TextView) mFooterView.findViewById(R.id.pulldown_footer_text);
        mFooterLoadingView = (ProgressBar) mFooterView.findViewById(R.id.pulldown_footer_loading);
        mFooterView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isAutoLoadMoreLoading) {
                    isAutoLoadMoreLoading = true;
                    mFooterTextView.setVisibility(View.INVISIBLE);
                    mFooterLoadingView.setVisibility(View.VISIBLE);
                    if(mOnPullDownListener != null) {
                        mOnPullDownListener.onMore();
                    }
                }
            }
        });
        if (attr != null) {
            initFooterBackground(attr);
        }
        getRefreshableView().addFooterView(mFooterView);
    }

    public void onLoadMoreComplete() {
        post(new Runnable() {
            @Override
            public void run() {
                isAutoLoadMoreLoading = false;
                mFooterTextView.setVisibility(View.VISIBLE);
                mFooterLoadingView.setVisibility(View.INVISIBLE);
            }
        });
    }

    /**
     * 设置监听器
     *
     * @param listener
     */
    public void setOnPullDownListener(OnPullDownListener listener) {
        mOnPullDownListener = listener;
    }

    /**
     * 刷新和获取更多事件接口
     */
    public interface OnPullDownListener {
        /** 刷新事件接口 这里要注意的是获取更多完 要关闭 刷新的进度条onRefreshComplete() **/
        void onRefresh();

        /** 刷新事件接口 这里要注意的是获取更多完 要关闭 更多的进度条 onLoadMoreComplete() **/
        void onMore();
    }

    /**
     * 条目是否填满整个屏幕
     */
    private boolean isFillScreenItem() {
        ListView listView = getRefreshableView();
        final int firstVisiblePosition = listView.getFirstVisiblePosition();
        final int lastVisiblePosition = listView.getLastVisiblePosition()
                - listView.getFooterViewsCount();
        final int visibleItemCount = lastVisiblePosition - firstVisiblePosition
                + 1;
        final int totalItemCount = listView.getCount() - listView.getFooterViewsCount();
        if (visibleItemCount < totalItemCount)
            return true;
        return false;
    }
}
